<?php
namespace app\admin\core;

use think\Cache;

class MpSession {
    const DEFAULT_PREFIX = '_common';
    private $_openid;
    private $_prefix = self::DEFAULT_PREFIX;
    public function __construct($openid){
        $this->_openid = $openid;
    }
    public function setPrefix($prefix) {
        $this->_prefix = $prefix;
    }
    public function set($name,$value) {
        $data = [$this->_prefix=>[$name => $value]];
        Cache::set($this->_openid,$data);
    }
    public function get($name) {
        $data = Cache::get($this->_openid);
//        if(!isset($data[$this->_prefix]) || !isset($data[$this->_prefix][$name])) {
        if(!isset($data[$this->_prefix][$name])) {
            return null;
        }
        return $data[$this->_prefix][$name];
    }

    /**
     * 删除整个session
     */
    public function clear() {
        Cache::rm($this->_openid);
    }

    /**
     * 删除某个键
     * @param null $name null的话，会删除整个prefix区域
     */
    public function rm($name = null) {
        $data = Cache::get($this->_openid);
        if($name) {
            unset($data[$this->_prefix][$name]);
            Cache::set($this->_openid,$data);
        }else {
            $data[$this->_prefix] = [];
            Cache::set($this->_openid,$data);
        }
    }
}